<template>
    <div class="team-detail-container">
        <!-- 顶部导航 -->
        <header class="header">
            <button class="back-btn" @click="goBack">
                <span class="back-icon">‹</span>
                返回
            </button>
        </header>

        <!-- 主要内容 -->
        <main class="队伍信息查看接口">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-container">
                <div class="loading-spinner"></div>
                <p class="loading-text">正在加载队伍详情...</p>
            </div>

            <!-- 错误提示 -->
            <div v-else-if="errorMessage" class="error-container">
                <div class="error-icon">⚠️</div>
                <p class="error-text">{{ errorMessage }}</p>
                <button class="retry-btn" @click="retryFetchTeamDetails">重试</button>
            </div>

            <!-- 成功提示 -->
            <div v-if="successMessage" class="success-toast">
                <div class="success-icon">✅</div>
                <p class="success-text">{{ successMessage }}</p>
            </div>

            <!-- 自定义编辑弹窗 -->
            <div v-if="dialogVisible" class="dialog-overlay" @click="cancelDialog">
                <div class="dialog-content" @click.stop>
                    <div class="dialog-header">
                        <h3 class="dialog-title">{{ dialogTitle }}</h3>
                        <button class="dialog-close-btn" @click="cancelDialog">×</button>
                    </div>
                    <div class="dialog-body">
                        <textarea v-model="dialogValue" :placeholder="dialogPlaceholder" class="dialog-input" rows="4"
                            @keydown.ctrl.enter="confirmDialog"></textarea>
                    </div>
                    <div class="dialog-footer">
                        <button class="dialog-btn cancel-btn" @click="cancelDialog">取消</button>
                        <button class="dialog-btn confirm-btn" @click="confirmDialog">确认</button>
                    </div>
                </div>
            </div>

            <!-- 主要内容 -->
            <div v-else>

                <!-- 队伍名称 -->
                <div class="team-name-section">
                    <h1 class="team-name">{{ teamInfo.teamName }}队</h1>
                    <button class="name-edit-btn" @click="editTeam" v-if="canEdit">✏️</button>
                </div>

                <!-- 用户角色标识 -->
                <div class="role-indicator">
                    <span class="role-badge" :class="userRole === 'instructor' ? 'instructor-badge' : 'expert-badge'">
                        {{ userRole === 'instructor' ? '指导老师' : '入驻专家' }}
                    </span>
                </div>

                <!-- 队伍成员 -->
                <div class="section">
                    <button class="manage-btn" v-if="canEdit" style="margin-left: auto;" @click="manageTeamMembers">
                        管理 📋
                    </button>
                    <div class="section-header">

                        <h2 class="section-title-main">队伍成员</h2>

                    </div>

                    <div class="members-grid-new">
                        <div v-for="member in teamMembers" :key="member.id" class="member-card-new">
                            <!-- 成员头像 -->
                            <div class="member-avatar-new">
                                <div class="avatar-circle-new">
                                    {{ member.realName.charAt(1) }}
                                </div>
                            </div>

                            <!-- 成员信息 -->
                            <div class="member-info-new">
                                <div class="member-name-new">{{ member.realName }}</div>
                                <div class="member-role-new">{{ member.memberRole }}</div>
                                <div class="member-college-new">{{ member.college }}</div>
                            </div>

                            <!-- 打分区域 -->
                            <div class="member-score-section" v-if="canEdit">
                                <div class="score-display">
                                    当前得分：{{ member.score || '0' }}/20
                                </div>
                                <div class="score-input-group">
                                    <input type="number" v-model="member.tempScore" :placeholder="member.score || '0'"
                                        min="0" max="20" step="0.1" class="score-input"
                                        @keyup.enter="submitScore(member)" />
                                    <button class="score-submit-btn" @click="submitScore(member)"
                                        :disabled="!member.tempScore || member.scoring">
                                        {{ member.scoring ? '提交中...' : '提交' }}
                                    </button>
                                </div>
                            </div>

                            <!-- 专家查看模式下的得分显示 -->
                            <div class="member-score-view" v-else>
                                <div class="score-display-readonly">
                                    队员得分：{{ member.score || '0' }}/20
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 指导老师 -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title-main">指导老师</h2>
                    </div>

                    <div class="teacher-container-horizontal">
                        <div class="teacher-card-horizontal">
                            <div class="teacher-avatar">
                                <img v-if="instructorInfo.avatar" :src="instructorInfo.avatar"
                                    :alt="instructorInfo.realName" class="avatar-img" />
                                <div v-else class="avatar-circle">
                                    {{ instructorInfo.realName ? instructorInfo.realName.charAt(0) : '老' }}
                                </div>
                            </div>
                            <div class="teacher-info-horizontal">
                                <div class="teacher-name">{{ instructorInfo.realName || '王老师' }}</div>
                                <div class="teacher-title">{{ instructorInfo.professionalTitle || '华南师范大学教授' }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 入驻专家 -->
                <div class="section">
                    <div class="section-header">
                        <h2 class="section-title-main">入驻专家</h2>
                    </div>

                    <div class="experts-container-horizontal">
                        <div v-if="teamExperts.length > 0" class="experts-list-horizontal">
                            <div v-for="expert in teamExperts" :key="expert.id" class="expert-card-horizontal">
                                <div class="expert-avatar">
                                    <img v-if="expert.avatar" :src="expert.avatar" :alt="expert.realName"
                                        class="avatar-img" />
                                    <div v-else class="avatar-circle">
                                        {{ expert.realName.charAt(0) }}
                                    </div>
                                </div>
                                <div class="expert-info-horizontal">
                                    <div class="expert-name">{{ expert.realName }}</div>
                                    <div class="expert-title">{{ expert.professionalTitle }}</div>
                                </div>
                            </div>
                        </div>

                        <div v-else class="no-experts">
                            <div class="empty-text">暂无入驻专家</div>
                        </div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-section">
                    <button class="action-btn primary" @click="showNotificationCenter">
                        通知中心
                    </button>
                </div>

                <!-- 团队介绍 -->
                <div class="section">
                    <div class="section-header">
                        <h3 class="section-title-main">团队介绍</h3>
                        <button class="edit-info-btn" @click="editTeamIntro" v-if="canEdit">✏️</button>
                    </div>
                    <div class="info-content">
                        <div v-if="teamInfo.teamIntro" class="info-display">
                            <div class="info-item">{{ teamInfo.teamIntro }}</div>
                        </div>
                        <div v-else class="empty-state">
                            <div class="empty-text">暂无团队介绍</div>
                        </div>
                    </div>
                </div>

                <!-- 当前参与的比赛 -->
                <div class="section">
                    <div class="section-header">
                        <h3 class="section-title-main">当前参与的比赛</h3>
                        <button class="edit-info-btn" @click="editCurrentCompetition" v-if="canEdit">✏️</button>
                    </div>
                    <div class="info-content">
                        <div v-if="currentCompetitions.length > 0" class="info-display">
                            <div v-for="(competition, index) in currentCompetitions" :key="index" class="info-item">
                                {{ competition }}
                            </div>
                        </div>
                        <div v-else class="empty-state">
                            <div class="empty-text">暂无参与的比赛信息</div>
                        </div>
                    </div>
                </div>

                <!-- 获奖情况 -->
                <div class="section">
                    <div class="section-header">
                        <h3 class="section-title-main">获奖情况</h3>
                        <button class="edit-info-btn" @click="editAwardInfo" v-if="canEdit">✏️</button>
                    </div>
                    <div class="info-content">
                        <div v-if="awards.length > 0" class="info-display">
                            <div v-for="(award, index) in awards" :key="index" class="info-item">
                                {{ award }}
                            </div>
                        </div>
                        <div v-else class="empty-state">
                            <div class="empty-text">暂无获奖信息</div>
                        </div>
                    </div>
                </div>

                <!-- 队伍基本信息 -->
                <!-- <div class="section"> -->
                <div class="team-meta-simple">
                    <span class="meta-info">队伍编号：{{ teamInfo.teamCode || '自动生成' }}</span>
                    <span class="meta-separator">|</span>
                    <span class="meta-info">组建时间：{{ formatDate(teamInfo.createTime) }}</span>
                </div>
                <!-- </div> -->
            </div>
        </main>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTeacherStore } from '@/stores/teacher.js'
import { getTeamDetailService, scoreMemberService, updateTeamInfoService } from '@/api/team.js'

const router = useRouter()
const route = useRoute()
const teacherStore = useTeacherStore()

// 响应式数据
const teamInfo = ref({
    id: null,
    teamName: '',
    teamCode: '',
    teamType: '',
    instructorId: null,
    teamIntro: '',
    currentCompetition: '',
    awardInfo: '',
    createTime: null,
    updateTime: null
})

const teamMembers = ref([])
const instructorInfo = ref({})
const teamExperts = ref([])

// 计算属性：当前参与的比赛列表
const currentCompetitions = ref([])
const awards = ref([])

// 加载状态和错误提示
const loading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 用户角色权限控制
const userRole = computed(() => {
    // 从路由查询参数获取角色信息
    return route.query.role || 'instructor' // 默认为指导老师
})

// 判断是否可以编辑（只有指导老师可以编辑）
const canEdit = computed(() => {
    return userRole.value === 'instructor'
})

// 自定义弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogPlaceholder = ref('')
const dialogValue = ref('')
const dialogCallback = ref(null)

// 显示自定义弹窗
const showDialog = (title, placeholder, defaultValue = '', callback) => {
    dialogTitle.value = title
    dialogPlaceholder.value = placeholder
    dialogValue.value = defaultValue
    dialogCallback.value = callback
    dialogVisible.value = true
}

// 确认弹窗
const confirmDialog = () => {
    if (dialogCallback.value) {
        dialogCallback.value(dialogValue.value)
    }
    dialogVisible.value = false
}

// 取消弹窗
const cancelDialog = () => {
    dialogVisible.value = false
    dialogValue.value = ''
}

// 显示成功提示
const showSuccess = (message) => {
    errorMessage.value = '' // 清除错误消息
    successMessage.value = message
    setTimeout(() => {
        successMessage.value = ''
    }, 3000)
}

// 页面挂载时的初始化
onMounted(async () => {
    console.log('队伍详情页面加载，用户角色:', userRole.value, '可编辑权限:', canEdit.value)

    // 从路由参数获取队伍信息
    if (route.params.teamData) {
        const teamData = JSON.parse(decodeURIComponent(route.params.teamData))
        initializeTeamData(teamData)
    } else if (route.params.teamId) {
        // 如果有队伍ID，从API获取完整的队伍信息
        await fetchTeamDetails(route.params.teamId)
    }
})

// 初始化队伍数据
const initializeTeamData = (data) => {
    teamInfo.value = data.teamInfo || {}

    // 处理队员数据，添加打分相关字段
    if (data.selectedStudents && Array.isArray(data.selectedStudents)) {
        teamMembers.value = data.selectedStudents.map(member => ({
            id: member.id,
            realName: member.realName || '未知姓名',
            studentId: member.id, // 使用id作为studentId
            studentNumber: member.studentId || '未知学号', // 学号
            college: member.college || '未知学院',
            memberRole: member.memberRole || '队员',
            score: 0, // 初始分数为0
            tempScore: '', // 临时分数输入
            scoring: false // 打分状态
        }))
    }

    // 优先使用传入的instructor信息，否则从store获取当前教师信息
    if (data.instructorInfo) {
        instructorInfo.value = data.instructorInfo
    } else {
        const currentTeacher = teacherStore.teacherInfo
        instructorInfo.value = {
            id: currentTeacher?.id,
            realName: currentTeacher?.realName || '当前教师',
            professionalTitle: currentTeacher?.professionalTitle || '指导教师',
            avatar: currentTeacher?.avatar
        }
    }

    teamExperts.value = data.experts || []

    // 解析比赛和获奖信息
    if (teamInfo.value.currentCompetition) {
        currentCompetitions.value = teamInfo.value.currentCompetition.split(';').filter(c => c.trim())
    }
    if (teamInfo.value.awardInfo) {
        awards.value = teamInfo.value.awardInfo.split(';').filter(a => a.trim())
    }
}

// 获取队伍详细信息（API调用）
const fetchTeamDetails = async (teamId) => {
    loading.value = true
    errorMessage.value = ''

    try {
        const response = await getTeamDetailService(teamId)
        if (response.code === 200 && response.data) {
            const teamData = response.data

            // 更新队伍基本信息
            teamInfo.value = {
                id: teamData.teamId, // 使用teamId而不是id
                teamName: teamData.teamName || '',
                teamCode: teamData.teamCode || '',
                teamType: teamData.teamType || '',
                instructorId: teamData.instructorId,
                teamIntro: teamData.teamIntro || '',
                currentCompetition: teamData.currentCompetition || '',
                awardInfo: teamData.awardInfo || '',
                createTime: teamData.createTime,
                updateTime: teamData.updateTime
            }

            // 更新队伍成员信息
            if (teamData.members && Array.isArray(teamData.members)) {
                teamMembers.value = teamData.members.map(member => ({
                    id: member.studentId,
                    realName: member.realName || '未知姓名',
                    studentId: member.studentId, // 这是实际的学生ID，用于API调用
                    studentNumber: member.studentNumber || '未知学号', // 这是学号，用于显示
                    college: member.college || '未知学院',
                    memberRole: member.memberRole || '队员',
                    score: member.score || 0, // 添加当前得分
                    tempScore: '', // 添加临时得分输入框
                    scoring: false // 添加打分状态
                }))
            }

            // 更新指导教师信息
            if (teamData.instructor) {
                instructorInfo.value = {
                    id: teamData.instructor.id,
                    realName: teamData.instructor.realName || '指导教师',
                    professionalTitle: teamData.instructor.professionalTitle || '教师',
                    avatar: teamData.instructor.avatar
                }
            } else {
                // 如果没有指导教师信息，使用当前教师信息
                const currentTeacher = teacherStore.teacherInfo
                instructorInfo.value = {
                    id: currentTeacher?.id,
                    realName: currentTeacher?.realName || '当前教师',
                    professionalTitle: currentTeacher?.professionalTitle || '指导教师',
                    avatar: currentTeacher?.avatar
                }
            }

            // 更新专家信息
            if (teamData.experts && Array.isArray(teamData.experts)) {
                teamExperts.value = teamData.experts.map(expert => ({
                    id: expert.id,
                    realName: expert.realName || '专家',
                    professionalTitle: expert.professionalTitle || '专家',
                    avatar: expert.avatar
                }))
            } else {
                teamExperts.value = []
            }

            // 解析比赛和获奖信息
            if (teamInfo.value.currentCompetition) {
                currentCompetitions.value = teamInfo.value.currentCompetition.split(';').filter(c => c.trim())
            } else {
                currentCompetitions.value = []
            }

            if (teamInfo.value.awardInfo) {
                awards.value = teamInfo.value.awardInfo.split(';').filter(a => a.trim())
            } else {
                awards.value = []
            }

            console.log('队伍详情获取成功:', teamData)
            console.log('队伍ID:', teamInfo.value.id) // 添加调试信息
        } else {
            console.error('获取队伍详情失败: 响应状态异常', response)
            errorMessage.value = '获取队伍详情失败，请稍后重试'
        }
    } catch (error) {
        console.error('获取队伍详情失败:', error)
        if (error.response) {
            console.error('错误响应:', error.response.data)
            errorMessage.value = error.response.data.message || '获取队伍详情失败，请稍后重试'
        } else {
            errorMessage.value = '网络连接异常，请检查网络后重试'
        }
    } finally {
        loading.value = false
    }
}

// 返回上一页
const goBack = () => {
    router.go(-1)
}

// 显示通知中心
const showNotificationCenter = () => {
    try {
        console.log('跳转到通知中心，队伍ID:', teamInfo.value.id, '用户角色:', userRole.value)
        router.push({
            name: 'NotificationCenter',
            params: { teamId: teamInfo.value.id },
            query: { role: userRole.value }
        })
    } catch (error) {
        console.error('跳转通知中心失败:', error)
        errorMessage.value = '跳转失败，请稍后重试'
    }
}

// 编辑队伍名称
const editTeam = () => {
    showDialog(
        '编辑队伍名称',
        '请输入新的队伍名称...',
        teamInfo.value.teamName,
        (newName) => {
            if (newName && newName.trim() && newName.trim() !== teamInfo.value.teamName) {
                updateTeamInfo({ teamName: newName.trim() })
            }
        }
    )
}

// 编辑团队介绍
const editTeamIntro = () => {
    showDialog(
        '编辑团队介绍',
        '请输入团队介绍内容...',
        teamInfo.value.teamIntro || '',
        (newIntro) => {
            updateTeamInfo({ teamIntro: newIntro.trim() })
        }
    )
}

// 编辑当前比赛
const editCurrentCompetition = () => {
    const currentText = currentCompetitions.value.join(';')
    showDialog(
        '编辑参与比赛',
        '请输入当前参与的比赛，多个比赛用分号(;)分隔...',
        currentText,
        (newCompetition) => {
            updateTeamInfo({ currentCompetition: newCompetition.trim() })
        }
    )
}

// 编辑获奖信息
const editAwardInfo = () => {
    const currentText = awards.value.join(';')
    showDialog(
        '编辑获奖情况',
        '请输入获奖情况，多个获奖用分号(;)分隔...',
        currentText,
        (newAward) => {
            updateTeamInfo({ awardInfo: newAward.trim() })
        }
    )
}

// 提交打分
const submitScore = async (member) => {
    if (!member.tempScore || member.scoring) return

    // 验证分数范围
    const score = parseFloat(member.tempScore)
    if (score < 0 || score > 20) {
        errorMessage.value = '分数必须在0-20分之间'
        return
    }

    member.scoring = true
    try {
        const scoreData = {
            teamId: teamInfo.value.id,
            studentId: member.studentId,
            score: score
        }

        console.log('提交打分数据:', scoreData) // 添加调试信息

        const response = await scoreMemberService(scoreData)
        if (response.code === 200) {
            member.score = score
            member.tempScore = ''
            showSuccess('打分成功！')
            console.log('打分成功')
            // 可以添加成功提示
        } else {
            console.error('打分失败:', response)
            errorMessage.value = response.message || '打分失败，请稍后重试'
        }
    } catch (error) {
        console.error('打分失败:', error)
        if (error.response) {
            console.error('错误响应:', error.response.data)
            errorMessage.value = error.response.data.message || '打分失败，请稍后重试'
        } else {
            errorMessage.value = '网络连接异常，请检查网络后重试'
        }
    } finally {
        member.scoring = false
    }
}

// 更新队伍信息的通用方法
const updateTeamInfo = async (updateData) => {
    loading.value = true
    try {
        const requestData = {
            teamId: teamInfo.value.id,
            ...updateData
        }

        console.log('更新队伍信息数据:', requestData) // 添加调试信息

        const response = await updateTeamInfoService(requestData)
        if (response.code === 200) {
            // 更新本地数据
            Object.assign(teamInfo.value, updateData)

            // 重新解析比赛和获奖信息
            if (updateData.currentCompetition !== undefined) {
                currentCompetitions.value = updateData.currentCompetition
                    ? updateData.currentCompetition.split(';').filter(c => c.trim())
                    : []
            }

            if (updateData.awardInfo !== undefined) {
                awards.value = updateData.awardInfo
                    ? updateData.awardInfo.split(';').filter(a => a.trim())
                    : []
            }

            console.log('队伍信息更新成功')
            showSuccess('信息更新成功！')
        } else {
            console.error('更新失败:', response)
            errorMessage.value = response.message || '更新失败，请稍后重试'
        }
    } catch (error) {
        console.error('更新失败:', error)
        if (error.response) {
            console.error('错误响应:', error.response.data)
            errorMessage.value = error.response.data.message || '更新失败，请稍后重试'
        } else {
            errorMessage.value = '网络连接异常，请检查网络后重试'
        }
    } finally {
        loading.value = false
    }
}

// 获取角色样式类
const getRoleClass = (role) => {
    const roleClasses = {
        '队长': 'role-leader',
        '副队长': 'role-vice-leader',
        '技术负责人': 'role-tech-lead',
        '项目经理': 'role-manager',
        '队员': 'role-member'
    }
    return roleClasses[role] || 'role-member'
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '暂无'
    const date = new Date(dateString)
    return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月${String(date.getDate()).padStart(2, '0')}日`
}

// 重试获取队伍详情
const retryFetchTeamDetails = () => {
    if (route.params.teamId) {
        fetchTeamDetails(route.params.teamId)
    }
}

// 跳转到队伍编辑页面
const manageTeamMembers = () => {
    router.push({
        name: 'CreateTeam',
        params: { teamId: teamInfo.value.id },
        query: { mode: 'edit' }
    })
}
</script>

<style scoped lang="scss">
@import '@/assets/css/team-detail.css';
</style>